﻿using System;
using System.Data.Common;
using Microsoft.Extensions.Logging;

namespace Quantum.Logging
{
    public class SqlServerLogger : ILogger
    {
        private LogLevel _monitorLevel;
        private string _connectionString = string.Empty;
        private string _logName { get; }

        public SqlServerLogger(string logName, SqlServerLoggerOptions options)
        {
            _logName = logName;
            _connectionString = options.ConnectionString;
            _monitorLevel = options.MonitorLevel;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            var message = formatter(state, exception);

            if (!string.IsNullOrEmpty(message) || exception != null)
            {
                WriteMessage(logLevel, _logName, eventId.Id, message, exception);
            }
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            if (logLevel == LogLevel.None)
            {
                return false;
            }

            return _monitorLevel <= logLevel;
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return null;
        }


        public virtual void WriteMessage(LogLevel logLevel, string logName, int eventId, string message, Exception exception)
        {
        }

        private static string GetLogLevelString(LogLevel logLevel)
        {
            switch (logLevel)
            {
                case LogLevel.Trace:
                    return "trce";
                case LogLevel.Debug:
                    return "dbug";
                case LogLevel.Information:
                    return "info";
                case LogLevel.Warning:
                    return "warn";
                case LogLevel.Error:
                    return "fail";
                case LogLevel.Critical:
                    return "crit";
                default:
                    throw new ArgumentOutOfRangeException(nameof(logLevel));
            }
        }
    }
}
